﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Person;
using ManagementApi.Models.ProjectLockOut;
using ManagementApi.Models.System.AuditLog;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using ManagementApi.Mvc.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules;
using Modules.Attachment;
using Modules.Audit;
using Modules.Project;
using PmSoft.Exceptions;
using static Modules.System.Flow.FlowConstants;

namespace ManagementApi.Controllers.CommanderPannel
{
    /// <summary>
    /// 停复工相关接口
    /// </summary>
    [Route("/api/v1/commander/projectLockOut")]
    [ApiController]
    [Authorize(Roles = "Commander")]
    [TypeFilter(typeof(RequireSelProjectActionFilter))]
    public class ProjectLockOutController : ControllerBase
    {
        private readonly ProjectLockOutService projectLockOutService;
        private readonly ProjectCommanderApplicationContext applicationContext;
        private readonly ProjectService projectService;
        private readonly IMapper mapper;
        private readonly ProjectAttachmentService projectAttachmentService;
        private readonly SysAuditLogService sysAuditLogService;
        private readonly ProjectOwnAuthorizer ownAuthorizer;

        public ProjectLockOutController(ProjectLockOutService projectLockOutService, ProjectCommanderApplicationContext applicationContext, IMapper mapper, ProjectService projectService, ProjectAttachmentService projectAttachmentService, SysAuditLogService sysAuditLogService, ProjectOwnAuthorizer ownAuthorizer)
        {
            this.projectLockOutService = projectLockOutService;
            this.applicationContext = applicationContext;
            this.mapper = mapper;
            this.projectService = projectService;
            this.projectAttachmentService = projectAttachmentService;
            this.sysAuditLogService = sysAuditLogService;
            this.ownAuthorizer = ownAuthorizer;
        }

        /// <summary>
        /// 获取停复工记录列表(分页)
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
		[HttpGet("page")]
        public ApiResult<PageDto<ProjectLockOutDto>> GetProjectLockOuts([FromQuery] ProjectLockOutQuery query, int pageNum = 1, int pageSize = 20)
        {
            query.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            var depts = projectLockOutService.GetProjectLockOuts(query, pageNum, pageSize);
            var dtos = depts.AsPageDto(source => { return source.AsDto(FlowEngine.建设单位审核, applicationContext); });
            return ApiResult<PageDto<ProjectLockOutDto>>.Success(dtos);
        }

        /// <summary>
        /// 获取停复工记录详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ApiResult<ProjectLockOutEditForm> Get(int id)
        {
            ProjectLockOut? projectLockOut = projectLockOutService.Get(id);
            if (projectLockOut == null) return ApiResult<ProjectLockOutEditForm>.Failure("停复工记录不存在");
            ProjectInfo? projectInfo = projectService.GetProjectInfo(projectLockOut.ProjectId);
            if (projectInfo == null) return ApiResult<ProjectLockOutEditForm>.Failure("项目信息不存在");
            ProjectLockOutEditForm form = new();
            mapper.Map(projectLockOut, form);
            form.ProjectName = projectInfo.Name;
            form.ProjectCode = projectInfo.PrjNum;
            form.LinkMan = projectInfo.LinkMan;
            form.LinkPhone = projectInfo.LinkPhone;

            #region 附件查询

            var attachments = projectAttachmentService.GetSysAttachmentByObjectIdAndType(projectLockOut.Id, 附件类型.停复工附件, 项目附件租户.LockOut);
            List<AttachmentsForm<int>> attach = new();
            foreach (var item in attachments)
            {
                AttachmentsForm<int> attachmentsForm = new()
                {
                    AttachmentId = item.Id,
                    AttachmentName = item.FriendlyName,
                };
                attach.Add(attachmentsForm);
            }
            form.Attachments = attach;

            #endregion 附件查询

            return ApiResult<ProjectLockOutEditForm>.Success(form);
        }

        /// <summary>
        /// 查询审核日志
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("auditLogs")]
        public ApiResult<IEnumerable<AuditLogDto>> GetSysAuditLogs(int id)
        {
            var data = sysAuditLogService.GetAuditLogsByObjectId(id, "project_lock_out");
            IEnumerable<AuditLogDto> auditLogDtos = data.AsDto();
            return ApiResult<IEnumerable<AuditLogDto>>.Success(auditLogDtos);
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="id"></param>
        /// <param name="auditForm"></param>
        /// <returns></returns>
        [HttpPut("audit/{id}")]
        public ApiResult Audit(int id, AuditForm auditForm)
        {
            #region 验证数据权限

            var data = projectLockOutService.Get(id) ?? throw new BusinessException("数据不存在");
            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(data.ProjectId);

            #endregion 验证数据权限

            projectLockOutService.Audit(id, auditForm.AuditIdea, auditForm.AuditIdeaContent, FlowEngine.建设单位审核);
            return ApiResult.Success("审核成功");
        }
    }
}